
package com.peanut.devlibrary.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class JsonUtils {


	public static HashMap<String, Object> fromJson(String jsonStr) {
		if(StringUtil.isNullOrEmpty(jsonStr)){
			return new HashMap<String, Object>();
		}
		try {
			JSONObject json = new JSONObject(jsonStr);
			return fromJson(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return new HashMap<String, Object>();
	}

	public static HashMap<String, Object> fromJson(JSONObject json) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			@SuppressWarnings("unchecked")
            Iterator<String> iKey = json.keys();
			while(iKey.hasNext()) {
				String key = iKey.next();
				Object value = json.opt(key);
				if (JSONObject.NULL.equals(value)) {
					value = null;
				}
				if (value != null) {
					if (value instanceof JSONObject) {
						value = fromJson((JSONObject)value);
					}
					else if (value instanceof JSONArray) {
						value = fromJson((JSONArray)value);
					}
					map.put(key, value);
				}
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return map;
	}

	public static ArrayList<Object> fromJson(JSONArray array)
			throws JSONException {
		ArrayList<Object> list = new ArrayList<Object>();
		for (int i = 0, size = array.length(); i < size; i++) {
			Object value = array.opt(i);
			if (value instanceof JSONObject) {
				value = fromJson((JSONObject)value);
			}
			else if (value instanceof JSONArray) {
				value = fromJson((JSONArray)value);
			}
			list.add(value);
		}
		return list;
	}

	/** 将指定的 {@link HashMap}<String, Object>对象转成json数据 */
	public static String fromHashMap(Map<String, Object> map) {
		try {
			return getJSONObject(map).toString();
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return "";
	}
	
	public static String fromArrayList(ArrayList<Object> list) {
		try {
			return getJSONArray(list).toString();
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return "";
	}

	@SuppressWarnings("unchecked")
	public static JSONObject getJSONObject(Map<String, Object> map)
			throws JSONException {
		JSONObject json = new JSONObject();
		for (Entry<String, Object> entry : map.entrySet()) {
			Object value = entry.getValue();
			if (value instanceof HashMap<?, ?>) {
				value = getJSONObject((HashMap<String, Object>)value);
			}
			else if (value instanceof ArrayList<?>) {
				value = getJSONArray((ArrayList<Object>)value);
			}
			json.put(entry.getKey(), value);
		}
		return json;
	}

	@SuppressWarnings("unchecked")
	public static JSONArray getJSONArray(ArrayList<Object> list)
			throws JSONException {
		JSONArray array = new JSONArray();
		for (Object value : list) {
			if (value instanceof HashMap<?, ?>) {
				value = getJSONObject((HashMap<String, Object>)value);
			}
			else if (value instanceof ArrayList<?>) {
				value = getJSONArray((ArrayList<Object>)value);
			}
			array.put(value);
		}
		return array;
	}
	
	/** 格式化一个json�? */
	public static String format(String jsonStr) {
		try {
			return format("", fromJson(jsonStr));
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return "";
	}

	@SuppressWarnings("unchecked")
	private static String format(String sepStr, HashMap<String, Object> map) {
		StringBuffer sb = new StringBuffer();
		sb.append("{\n");
		String mySepStr = sepStr + "\t";
		int i = 0;
		for (Entry<String, Object> entry : map.entrySet()) {
			if (i > 0) {
				sb.append(",\n");
			}
			sb.append(mySepStr).append('\"').append(entry.getKey()).append("\":");
			Object value = entry.getValue();
			if (value instanceof HashMap<?, ?>) {
				sb.append(format(mySepStr, (HashMap<String, Object>)value));
			}
			else if (value instanceof ArrayList<?>) {
				sb.append(format(mySepStr, (ArrayList<Object>)value));
			}
			else if (value instanceof String) {
				sb.append('\"').append(value).append('\"');
			}
			else {
				sb.append(value);
			}
			i++;
		}
		sb.append('\n').append(sepStr).append('}');
		return sb.toString();
	}

	@SuppressWarnings("unchecked")
	private static String format(String sepStr, ArrayList<Object> list) {
		StringBuffer sb = new StringBuffer();
		sb.append("[\n");
		String mySepStr = sepStr + "\t";
		int i = 0;
		for (Object value : list) {
			if (i > 0) {
				sb.append(",\n");
			}
			sb.append(mySepStr);
			if (value instanceof HashMap<?, ?>) {
				sb.append(format(mySepStr, (HashMap<String, Object>)value));
			}
			else if (value instanceof ArrayList<?>) {
				sb.append(format(mySepStr, (ArrayList<Object>)value));
			}
			else if (value instanceof String) {
				sb.append('\"').append(value).append('\"');
			}
			else {
				sb.append(value);
			}
			i++;
		}
		sb.append('\n').append(sepStr).append(']');
		return sb.toString();
	}
	
	// ----------json解析
	public static boolean isNull(String str) {
		if (str == null || "".equals(str.trim()) || "null".equals(str.trim()))
			return true;
		return false;
	}
	// optString()这个方法可以在value没有数据的时候返回null值
	public static String JSONString(JSONObject obj, String name)
			throws JSONException {
		if (!isNull(obj.optString(name))) {
			return obj.optString(name);
		}
		return "";
	}

	public static int JSONInter(JSONObject obj, String name)
			throws JSONException {

		if (!isNull(obj.optString(name))) {
			return obj.optInt(name);
		}
		return 0;
	}

	public static Long JSONLong(JSONObject obj, String name)
			throws JSONException {
		if (!isNull(obj.optString(name))) {
			return obj.optLong(name);
		}
		return 0L;
	}

	public static boolean JSONBoolean(JSONObject obj, String name)
			throws JSONException {
		if (!isNull(obj.optString(name))) {
			return obj.optBoolean(name);
		}
		return false;
	}

	public static double JSONDouble(JSONObject obj, String name)
			throws JSONException {
		if (!isNull(obj.optString(name))) {
			return obj.optDouble(name);
		}
		return 0;
	}
	
	public static boolean checkCode(String data) {
		if (StringUtil.isNullOrEmpty(data))
			return false;
		try {
			JSONObject json = new JSONObject(data);
			return JsonUtils.JSONString(json, "code").equalsIgnoreCase("0");
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		} 
	}
	
	public static String checkError(String data) {
		if (StringUtil.isNullOrEmpty(data))
			return "";
		try {
			JSONObject json = new JSONObject(data);
			return JsonUtils.JSONString(json, "error");
		} catch (JSONException e) {
			e.printStackTrace();
			return "";
		} 
	}
}
